import json
import time
import hmac
import hashlib
import base64
import urllib.parse
import requests


class DingTalkUtil:

    def __init__(self):
        self.secret = "SEC64b32889ec339111574aeec98eaca8ed2ad98ebde737472622ea8678546a1678"
        self.url = "https://oapi.dingtalk.com/robot/send?access_token=aad7ffb1ae44ccad27e8c3c6db1ba89f58827737bc83a555459e111cfadae0a7"
        self.timestamp = ""
        self.sign = ""
        self.json = "{\"at\": {\"isAtAll\": false},\"text\": {\"content\": \"%s\"},\"msgtype\": \"text\"}"

    def send_text(self, content):
        self.create_sign()
        url = self.url + "&sign=%s&timestamp=%s" % (self.sign, self.timestamp)
        json_content = json.loads(self.json % content, strict=False)
        headers = {"Content-Type": "application/json ;charset=utf-8 "}
        try:
            response = requests.post(url, headers=headers, json=json_content, timeout=(3, 60))
            response_msg = str(response.status_code) + ' ' + str(response.content.decode('utf-8'))
            print(response_msg)
        except Exception as error_msg:
            print('error_msg===' + str(error_msg))

    def create_sign(self):
        self.timestamp = str(round(time.time() * 1000))
        secret_enc = self.secret.encode('utf-8')
        string_to_sign = '{}\n{}'.format(self.timestamp, self.secret)
        string_to_sign_enc = string_to_sign.encode('utf-8')
        hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
        self.sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))